/*DS18B20温度传感器底层onewire代码 及 DS18B20上层函数*/

#include "onewire.h"

//单总线延时函数
void Delay_OneWire( unsigned int t )  
{
	unsigned char i;
	while (t --)
	{
		for (i = 0; i < 8; i ++);
	}
}
/*初始化
	主机 将总线拉低至少480us，然后释放总线，
	等待15~60us后，存在的 从机 会拉低总线60~240us以响应 主机
	之后 从机 将释放总线
*/
//DS18B20设备初始化
bit OneWire_Init(void)
{
  	bit ackbit = 0;
  	
  	OneWire_DQ = 1;	Delay_OneWire(12);
  	OneWire_DQ = 0; Delay_OneWire(80);
  	OneWire_DQ = 1; Delay_OneWire(10); 
    ackbit = OneWire_DQ;Delay_OneWire(5);
	
  	return ackbit;
}


//通过单总线向DS18B20温度传感器写(发送)一个字节
void WriteByte_DS18B20(unsigned char dat)
{
	unsigned char i;
	for (i = 0; i < 8; i ++)
	{
		OneWire_DQ = 0;
		OneWire_DQ = dat & 0x01;
		Delay_OneWire(5);
		OneWire_DQ = 1;
		dat >>= 1;
	}
	Delay_OneWire(5);
}

//从DS18B20读取一个字节
unsigned char ReadByte_DS18B20(void)
{
	unsigned char i;
	unsigned char dat;
  
	for (i = 0; i < 8; i ++)
	{
		OneWire_DQ = 0;
		dat >>= 1;
		OneWire_DQ = 1;
		if (OneWire_DQ)
		{
			dat |= 0x80;
		}	    
		Delay_OneWire(5);
	}
	return dat;
}

float DS18B20_GetTemperature(void) //DS18B20读取温度
{
	unsigned char low,high;
	float re_value;
	
	OneWire_Init();
	WriteByte_DS18B20(0xcc);
	WriteByte_DS18B20(0X44);
	Delay_OneWire(20);
	OneWire_Init();
	WriteByte_DS18B20(0xcc);
	WriteByte_DS18B20(0xbe);
	low=ReadByte_DS18B20();
	high=ReadByte_DS18B20();
//	re_value=(high<<4)|(low>>4);整数
	
	//精度为0.0625摄氏度
	re_value=(high<<8|low)/16.0;

	return re_value;
}
